<template>
  <el-container id="rootBox" ref="rootBox" class="rootBox">
    <el-main style="    padding-top: 0px;">
      <small>1、添加新项请先加锁【init-data-sql.json】。2：修改单个sql不用加锁init-data-sql.json，点击左侧sql文件进行修改即可</small>
      <el-row style="border: 2px red dotted; padding: 6px 11px;" >
        <el-col :span="24">
          init-data-sql.json状态：

          <el-button type="primary" @click="handleAdd"  style="width:75px;" :disabled="mainInfo.lockStatus != 'LOCK_BY_SELF'">添加项</el-button>
          <svn-box
            ref="svnMain"
            propSourceType="init-data"
            :propShowAdd="false"
            :propShowDelete="false"
            @set-loading="handleSvnSetLoading" style="    display: inline-block;"
            @lock-status-change="handleLockStatusChangeMain"
          />

          <el-popover
            placement="bottom"
            title=""
            width="400"
            trigger="manual"
            v-model="visible">

            <el-form class="input-form" label-position="right" label-width="120px" ref="editForm"
                     :model="addForm">
              <el-row  >
                <el-col :span="24">
                  <el-form-item label="类型" required prop="type">
                    <el-select v-model="addForm.type">
                      <el-option v-for="qt in types" :key="qt.value" :value="qt.value" :label="qt.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row  >
                <el-col :span="24">
                  <el-form-item label="表名" required prop="tables">
                    <el-input v-model="addForm.tables" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row  >
                <el-col :span="24">
                  <el-form-item label="描述" required prop="description">
                    <el-input v-model="addForm.description" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row  >
                <el-col :span="24">
                  <el-form-item label="作者" required prop="author">
                    <el-input v-model="addForm.author" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row  >
                <el-col :span="24">
                  <el-form-item label="id" required prop="id">
                    <el-input v-model="addForm.id" disabled/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row  >
                <el-col :span="24">
                  <el-form-item>
                    <el-button type="primary" @click="addNew">添加</el-button>
                    <el-button type="" @click="addNewCancel">取消</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-popover>
        </el-col>
      </el-row>
        <el-row >
          <el-col :span="4">
            <el-input ref='keyPage' v-model="keyPage" autofocus="true" placeholder="搜索表名/描述" style="width:300px;width: 200px;margin-left: 50px;" clearable></el-input>
            <div :style="{maxHeight: maxH+'px',overflow: 'auto'}">

              <el-menu
                @open="handleOpen"
                :default-openeds = "['1','2','3']"
                @close="handleClose">
                <el-submenu index="1" >
                  <template slot="title">
                    <span>数据类</span>
                  </template>
                  <el-menu-item  :index="'1-'+index" :key="item.tables" v-for="(item, index) in searchPage" v-if="item.type == 'data'" @click="tabClick(item)"  >
                    <div class="label-box" >
                      {{item.id}}，{{item.tables}}，{{item.description}}
                    </div>
                  </el-menu-item>
                </el-submenu>
                <el-submenu index="2">
                  <template slot="title">
                    <span>视图类</span>
                  </template>
                  <el-menu-item  :index="'2-'+index" :key="item.tables" v-for="(item, index) in searchPage" v-if="item.type == 'view'" @click="tabClick(item)"  >
                    <div class="label-box" >
                      {{item.id}}，{{item.tables}}，{{item.description}}
                    </div>
                  </el-menu-item>
                </el-submenu>
                <el-submenu index="3">
                  <template slot="title">
                    <span>系统配置</span>
                  </template>
                  <el-menu-item  :index="'1-'+index" :key="item.tables" v-for="(item, index) in searchPage" v-if="item.type == 'config'" @click="tabClick(item)"  >
                    <div class="label-box" >
                      {{item.id}}，{{item.tables}}，{{item.description}}
                    </div>
                  </el-menu-item>
                </el-submenu>
                <el-submenu index="3">
                  <template slot="title">
                    <span>未知类型</span>
                  </template>
                  <el-menu-item  :index="'1-'+index" :key="item.tables" v-for="(item, index) in searchPage" v-if="strings.isBlank(item.type)" @click="tabClick(item)"  >
                    <div class="label-box" >
                      {{item.id}}，{{item.tables}}，{{item.description}}
                    </div>
                  </el-menu-item>
                </el-submenu>
              </el-menu>

              <!--<el-tabs v-model="navValue"   tab-position="left" id="tabs" @tab-click="tabClick">
                <el-tab-pane
                  :key="item.tables"
                  :name="item.tables"
                  v-for="(item, index) in searchPage"
                  :label="item.tables+'-'+ item.description"
                  :data="searchPage"
                >
                  <template slot="label">
                    <div class="label-box" >
                      id：{{item.id}}<br>
                      表名：{{item.tables}} <br>
                      描述：{{item.description}}
                    </div>
                  </template>
                </el-tab-pane>
              </el-tabs>-->
            </div>
          </el-col>
          <el-col :span="20">
            <el-row style="margin-bottom:10px;">
              <el-col :span="24">
                <h4 v-if="strings.isNotBlank(editCurr.tables)">
                  <span style="margin-right: 11px">当前编辑文件： {{'init-data/'+editCurr.tables+'.txt' }}，</span>
                  <span style="margin-right: 11px">最近修改人：{{editCurr.author}}</span>
                  最新修改时间：{{editCurr.time}}
                </h4>
                <h4 v-else>当前编辑文件： 无
                </h4>
              </el-col>
            </el-row>
            <el-row >
              <el-col :span="8">
                  <el-button type="primary" @click="handleSave" :disabled="disabled" >保存到文件</el-button>
                  <el-button type="danger" @click="handleExecute(true)" :disabled="disabled" >执行当前sql</el-button>
                  <el-button type="danger" @click="handleExecute" >执行全部sql</el-button>
                  <el-button type="danger" @click="splitAll()" >拆分init-data-sql.json</el-button>
              </el-col>
              <el-col :span="16">
                <svn-box
                  ref="svn"
                  propSourceType="init-data-sql"
                  :propShowAdd="false"
                  :propShowDelete="false"
                  @set-loading="handleSvnSetLoading"
                  @lock-status-change="handleLockStatusChange"
                />
              </el-col>
            </el-row>

            <el-row >
              <el-col :span="24" >
                <div :style="{height: maxH-60+'px',overflow: 'auto'}">
                  <codemirror :disabled="disabled"   ref="sqlCode" v-model="fileTxt" :options="editOptions"  ></codemirror>
                </div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
    </el-main>
  </el-container>
</template>

<script>
/* eslint-disable*/
import SvnBox from '@/components/SvnBox.vue'
import { codemirror } from 'vue-codemirror'
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/theme/monokai.css'
import'codemirror/addon/selection/active-line.js'
import'codemirror/addon/selection/mark-selection.js'
import'codemirror/addon/search/searchcursor.js'
import'codemirror/addon/hint/show-hint.js'
import'codemirror/addon/hint/show-hint.css'
import'codemirror/addon/hint/javascript-hint.js'
import'codemirror/addon/selection/active-line.js'
import'codemirror/addon/scroll/annotatescrollbar.js'
import'codemirror/addon/search/matchesonscrollbar.js'
import'codemirror/addon/search/searchcursor.js'
import'codemirror/addon/search/match-highlighter.js'
import'codemirror/mode/clike/clike.js'
import'codemirror/addon/edit/matchbrackets.js'
import'codemirror/addon/comment/comment.js'
import'codemirror/addon/dialog/dialog.js'
import'codemirror/addon/dialog/dialog.css'
import'codemirror/addon/search/searchcursor.js'
import'codemirror/addon/search/search.js'
import'codemirror/keymap/sublime.js'
import'codemirror/addon/fold/foldgutter.css'
import'codemirror/addon/fold/brace-fold.js'
import'codemirror/addon/fold/comment-fold.js'
import'codemirror/addon/fold/foldcode.js'
import'codemirror/addon/fold/foldgutter.js'
import'codemirror/addon/fold/indent-fold.js'
import'codemirror/addon/fold/markdown-fold.js'
import'codemirror/addon/fold/xml-fold.js'
// 核心样式
import 'codemirror/lib/codemirror.css'

export default {
  name: 'frameInitData',
  data() {
    return {
      selectedTab: null,
      sqlStore: {},
      filter: '',
      svnUserName: '',
      loading: false,
      disabled: true,
      maxH: window.innerHeight - 280,
      rules: {
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        tables: [
          { required: true, message: '请描述要操作的表', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        sql: [
          { required: true, message: '请输入处理的SQL', trigger: 'blur' },
          { min: 10, max: 50000, message: '长度在 10 到 50000 个字符', trigger: 'blur' }
        ]
      },
      keyPage: '',
      navTabs: [
      ],
      navValue: '',
      fileName: '',
      fileTxt: '',
      editOptions: {
        tabSize: 4,
        styleActiveLine: true,
        lineNumbers: true,
        styleSelectedText: false,
        line: true,
        foldGutter: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
        highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
        mode: "text/html",
        // hint.js options
        hintOptions:{
          completeSingle: false
        },
        keyMap: "sublime",
        matchBrackets: true,
        showCursorWhenSelecting: true,
        theme: "monokai",
        extraKeys: { "Ctrl": "autocomplete" },
      },
      visible: false,
      addForm: {},
      editCurr: {},
      mainInfo: {},
      types: [
        { value: 'data', label: '数据，比如初始化数据' },
        { value: 'config', label: '系统配置类，比如默认机构、用户、报表、图表等' },
        { value: 'view', label: '数据库视图' },
      ],
    }
  },
  components: {
    SvnBox, codemirror
  },
  mounted() {
    // this.$refs.svn.ocSetFileName()
    this.handleRefresh()
    this.getMainLock()
  },
  computed: {
    searchPage: function() {
      if (this.keyPage) {
        return this.sqlStore.items.filter(ob => {
          if ( ob.tables.includes(this.keyPage) || (ob.tables+'').toLowerCase().indexOf(this.keyPage.toLowerCase()) != -1
          ||  ob.description.includes(this.keyPage) || (ob.description+'').toLowerCase().indexOf(this.keyPage.toLowerCase()) != -1
          ) {
            return ob;
          }
        });
      }
      return this.sqlStore.items;
    }
  },
  methods: {
    handleNodeClick(node, data) {
      this.selectedMenu = data
    },
    getFormName(id) {
      return 'form_' + id
    },
    getMaxId() {
      return this.sqlStore.lastId ? this.sqlStore.lastId : 0
    },
    handleRemove(item, index) {
      this.sqlStore.items.splice(index, 1)
      this.sqlStore.count = this.sqlStore.items.length
    },
    handleAdd() {
      this.visible = !this.visible
      this.addForm = {
        id: this.getMaxId() + 1,
        author: this.svnUserName,
        time: global.utils.now(),
        tables: '',
        description: '',
      }
    },
    // == SVN START===
    handleSvnSetLoading(loading) {
      this.loading = loading
    },
    handleLockStatusChange(status) {
      this.disabled = !['LOCK_BY_SELF', 'DRAFT', 'ADDED'].includes(status.lockStatus)
      this.svnUserName = status.userName
      // 锁定时要先获取最新版本，所以要重新获取记录
      if (status.lockStatus == 'LOCK_BY_SELF') {
        this.handleRefresh()
      }
    },
    handleLockStatusChangeMain(status) {
      this.disabledMain = !['LOCK_BY_SELF', 'DRAFT', 'ADDED'].includes(status.lockStatus)
      this.svnUserName = status.userName
      // 锁定时要先获取最新版本，所以要重新获取记录
      // if (status.lockStatus == 'LOCK_BY_SELF') {
      //   this.handleRefresh()
      // }
      this.mainInfo = status
    },
    // == SVN END==
    handleRefresh() {
      this.loading = true
      this.$ajax.get('/program/initData/getList').then(res => {
        this.sqlStore = JSON.parse(res.data)
      }).finally(() => {
        this.loading = false
      })
    },
    async handleExecute(isOne) {
      let title=`是否执行全部sql文件?`
      let toUrl='/program/initData/execute'
      if (isOne == true) {
        title=`是否执行当前sql文件，【init-data/${this.editCurr.tables}.txt】?`
        toUrl=`/program/initData/execute?fileName=${this.editCurr.tables}`
      }
      const result = await this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
      })
      if (!result)  return

      this.utilVue.loadShow(true)
      this.$ajax.post(toUrl).then(res => {
        this.utilMessage.success(res.msg)
        this.utilVue.loadHide()
      }).finally(() => {
      })
    },
    asyncValidate(form) {
      return new Promise((resolve, reject) => {
        form.validate((state) => {
          resolve(state)
        })
      })
    },
    async handleSave() {
      this.loading = true
      this.sqlStore.count = this.sqlStore.items.length

      let param ={
        fileName: this.fileName,
        sql: this.fileTxt
      }
      this.utilVue.loadShow(true)
      this.$ajax.post('/program/initData/saveSql', param).then(resp => {
        if ( resp.code == 0 ){
          this.utilMessage.success(resp.msg)
        }
        this.utilVue.loadHide()
      })
    },

    async handleSaveMain(isAdd) {
      let isOk = false
      this.utilVue.loadShow(true)
      this.sqlStore.count = this.sqlStore.items.length
      this.$ajax.post('/program/initData/save', { contents: JSON.stringify(this.sqlStore) }).then(res => {
        if (res.code == 0) {
          isOk = true
          this.utilMessage.success('init-data-sql.json 数据保存成功！')

          this.visible = !this.visible
          this.fileName = this.addForm.tables
          this.svnHandleRefresh()
          this.navValue = this.fileName
          this.$refs.sqlCode.setCursor(this.$refs.sqlCode.lineCount(), 0);
        }
        this.utilVue.loadHide()
      })
      return isOk
    },

    tabClick(tab) {
      console.log('tab', tab)
      this.fileName = tab.tables
       this.svnHandleRefresh()
    },
    async splitAll() {
      const result = await this.$confirm("是否拆分init-data-sql.json文件，创建不存在的sql文件。仅用于第一次项目合并后，仅开发环境使用", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
      })
      if (!result)  return

      this.utilVue.loadShow(true)
      this.$ajax.get(`/program/initData/splitAll` ).then((response) => {
        if(response.code == 0 ){
          this.utilMessage.success(response.msg)
        }
        this.utilVue.loadHide()
      })
    },

    async addNew() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.sqlStore.items.unshift(this.addForm)
          this.sqlStore.count = this.sqlStore.items.length
          this.sqlStore.lastId = this.addForm.id
          this.handleSaveMain(true)

        } else {
          return false;
        }
      })

    },
     addNewCancel() {
       this.visible = !this.visible
    },

    async svnHandleRefresh() {
      await this.$refs.svn.handleRefreshOut(this.fileName)
      this.getSql()

      this.editCurr = {}
       let findArr= this.sqlStore.items.filter(item => item.tables == this.fileName)
      if (findArr && findArr.length > 0) this.editCurr = findArr [0]
      console.log('this.editCurr', this.editCurr)
    },


    getSql(name) {
      this.utilVue.loadShow(true)
      this.$ajax.get(`/program/initData/getSql?fileName=${this.fileName}` ).then((response) => {
        if(response.code == 0 ){
          this.fileTxt = response.data.join('\r\n')
          this.$refs.sqlCode.refresh()
        }
        this.utilVue.loadHide()
      })
    },

    getMainLock() {

      this.$refs.svnMain.handleRefresh()
    }
  }
}
</script>

<style lang="scss" scoped>

  .rootBox{
    .el-tabs /deep/ {
      .el-tabs__item{
        height: 70px !important;
        padding-left: 0px;
        text-align: left;
      }

      .label-box{
        line-height: 20px;
        font-size: 14px;
      }
      .el-tabs__header{
        width: 100%;
      }
    }

    .CodeMirror  /deep/{
      overflow-y: auto  !important;
      height: auto !important;
    }
    .vue-codemirror  /deep/{
      overflow-y: auto  !important;
      height: auto !important;
    }

    .el-menu-item{
      font-size: 13px !important;
    }
    .el-submenu .el-menu-item{
      height: 30px;
      line-height: 30px;
      padding: 0 5px;
      min-width: 200px;
      text-align: left;
    }
  }





</style>
